// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: 'education-6gwexwp8488514df' }) // 使用你的云环境ID

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const { bookId, addressId, userId } = event

  try {
    // 检查是否已经添加过
    const countResult = await db.collection('bookAddresses')
      .where({
        bookId,
        addressId,
        userId
      })
      .count()

    if (countResult.total > 0) {
      return {
        success: false,
        error: 'ADDRESS_EXISTS'
      }
    }

    // 添加关联
    await db.collection('bookAddresses').add({
      data: {
        bookId,
        addressId,
        userId,
        createTime: db.serverDate()
      }
    })

    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      error: err
    }
  }
} 